﻿using System;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Runtime.Serialization;

namespace Portal.Data.Entity
{
    [Table(Name = "dbo.BookType"), Serializable, DataContractAttribute]
    public class BookType : BaseObject
    {
        #region Properties
        [Column(IsPrimaryKey = true)]
        public int TypeId { get; set; }
        [Column]
        public string BookIds { get; set; }
        #endregion

        #region Methods
        /// <summary>
        /// remove and added new values by BookId
        /// </summary>
        /// <param name="bookId"></param>
        /// <param name="typeIds"></param>
        public static void ChangedType(int bookId, int[] typeIds)
        {
            var sql = string.Format("update Book SET HistoryTypeIds='{0}' where ID={1};", string.Join(",", typeIds), bookId);    //update book
            using (var context = new CmsDataContext())
            {
                //first: lấy danh sách TypeIds cũ
                var sOldTypeIds = context.Books.Where(x => x.ID == bookId).Select(x => x.HistoryTypeIds).FirstOrDefault();
                var oldTypeIds = (sOldTypeIds != null) ? 
                    sOldTypeIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x)).ToArray() :
                    new int[] { };

                var newTypeIds = typeIds.Except(oldTypeIds);
                var removerTypeIds = oldTypeIds.Except(typeIds);
                sql = newTypeIds.Aggregate(sql, (current, typeId) => current + GetSqlAddBook(typeId, bookId));
                sql = removerTypeIds.Aggregate(sql, (current, typeId) => current + GetSqlAddBook(typeId, bookId));

                var sqlAddBookType = typeIds.Aggregate("", (current, typeId) => current + GetSqlAddBook(typeId, bookId));

                context.ExecuteCommand(sql + sqlAddBookType);
            }
        }

        /// <summary>
        /// Thêm 1 book vào danh sách Thể Loại
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="bookId"></param>
        public static void AddBook(int typeId, int bookId)
        {
            var sql = GetSqlAddBook(typeId, bookId);
            if (sql.Length > 0)
            {
                using (var context = new CmsDataContext())
                {
                    context.ExecuteCommand(sql);
                }
            }
        }


        /// <summary>
        /// Xóa 1 book khỏi danh sách thể loại
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="bookId"></param>
        public static void RemoveBook(int typeId, int bookId)
        {
            var sql = GetSqlRemoveBook(typeId, bookId);
            if (sql.Length > 0)
            {
                using (var context = new CmsDataContext())
                {
                    context.ExecuteCommand(sql);
                }
            }
        }
        public static int[] GetBookIds(int typeId)
        {
            using (var context = new CmsDataContext())
            {
                var bookIds = context.BookTypes.Where(x => x.TypeId == typeId).Select(x => x.BookIds).FirstOrDefault();
                return bookIds != null ? bookIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToInt32(n)).ToArray() : new int[] { };
            }
        }

        /// <summary>
        /// Tạo câu lệnh Insert hoặc Update book trong BookType
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="bookId"></param>
        /// <returns></returns>
        public static string GetSqlAddBook(int typeId, int bookId)
        {
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookTypes.Where(x => x.TypeId == typeId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var full = "," + bookids + ",";
                    if (full.IndexOf("," + bookId + ",") < 0)
                    {
                        bookids += "," + bookId;
                        return string.Format("update BookType set BookIds='{0}' where TypeId={1};", bookids, typeId);
                    }
                }
                else
                {
                    return string.Format("insert into BookType(TypeId,BookIds) values({0},'{1}');", typeId, bookId);
                }
            }
            return "";
        }

        /// <summary>
        /// Lấy câu lệnh xóa 1 book khỏi danh sách thể loại
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="bookId"></param>
        /// <returns></returns>
        public static string GetSqlRemoveBook(int typeId, int bookId)
        {
            using (var context = new CmsDataContext())
            {
                var bookids = context.BookTypes.Where(x => x.TypeId == typeId).Select(x => x.BookIds).FirstOrDefault();
                if (bookids != null)
                {
                    var bids =
                        bookids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => Convert.ToInt32(n))
                            .ToList();
                    if (bids.Contains(bookId))
                    {
                        bids.Remove(bookId);
                        bookids = string.Join(",", bids);   //new values
                        return string.Format("update BookType set BookIds={0} where TypeId={1}", bookids, typeId);
                    }
                }
            }
            return "";
        }
        #endregion Methods
    }
}
